package com.test;

import cn.hutool.core.io.BufferUtil;
import cn.hutool.core.io.IORuntimeException;
import cn.hutool.core.io.IoUtil;
import cn.hutool.core.lang.Console;
import cn.hutool.core.util.StrUtil;
import cn.hutool.socket.nio.NioServer;
import com.alibaba.fastjson2.JSONObject;
import com.test.enums.ActionType;
import com.test.utils.SocketResponseUtils;
import com.test.vo.RequestVo;
import org.apache.commons.lang3.StringUtils;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.TimeUnit;

/**
 * 模拟Socket服务端
 *
 * @author sangkuofeng
 * @date 2024/3/24 11:02
 */
public class HutoolServer {


    /**
     * 模拟返回
     *
     * @param args
     */
    public static void main(String[] args) {
        NioServer server = new NioServer(6002);
        server.setChannelHandler((sc) -> {
            ByteBuffer readBuffer = ByteBuffer.allocate(2048);
            try {
                //从channel读数据到缓冲区
                int readBytes = sc.read(readBuffer);
                if (readBytes > 0) {
                    //Flips this buffer.  The limit is set to the current position and then
                    // the position is set to zero，就是表示要从起始位置开始读取数据
                    readBuffer.flip();
                    //eturns the number of elements between the current position and the  limit.
                    // 要读取的字节长度
                    byte[] bytes = new byte[readBuffer.remaining()];
                    //将缓冲区的数据读到bytes数组
                    readBuffer.get(bytes);
                    String body = StrUtil.utf8Str(bytes);
                    Console.log("[{}]: {}", sc.getRemoteAddress(), body);
                    doWrite(sc, body);
                } else if (readBytes < 0) {
                    IoUtil.close(sc);
                }
            } catch (IOException e) {
                throw new IORuntimeException(e);
            }
        });
        server.listen();

    }

    public static void doWrite(SocketChannel channel, String response) throws IOException, InterruptedException {
        Console.log("收到消息：" + response);
        //将缓冲数据写入渠道，返回给客户端
        try {
            TimeUnit.MILLISECONDS.sleep(600);
        } catch (InterruptedException e) {}
        RequestVo requestVo = JSONObject.parseObject(response, RequestVo.class);
        if (StringUtils.equalsIgnoreCase(ActionType.SUBSCRIBE.getCode(), requestVo.getAction())) {
            String result = SocketResponseUtils.subscribe(requestVo.getRequestId());
            Console.log("返回结果: " + result);
            int count = 0;
            while (count < 10000){
                try {
                    TimeUnit.MILLISECONDS.sleep(10);
                } catch (InterruptedException e) {}
                channel.write(BufferUtil.create(result, Charset.forName("gb2312")));
            }
        } else {
            String result = SocketResponseUtils.getReturnResult(response);
            Console.log("返回结果: " + result);
            channel.write(BufferUtil.create(result, Charset.forName("gb2312")));
        }


    }


}
